import Response from '../../utils/response.js';
import { waterApi, shjApi } from '../../utils/request.js';
import { BzSource } from '../../utils/modules.js';

const bzSourceList = BzSource();

// 获取泵站列表
export const getList = async (ctx) => {
  try {
    // 创建参数对象
    const params = new URLSearchParams();

    params.append('pageSize', 1000);
    
    const isTotal = ctx.request.body.isTotal;
    const vision = ctx.request.body.vision;
    const queryName = ctx.request.body.name;
    const queryArea = ctx.request.body.area;
    const queryTown = ctx.request.body.town;
    const querySource = ctx.request.body.source;
    const pageNum = ctx.request.body.pageNum || 1;
    const pageSize = ctx.request.body.pageSize || 10;
    
    if (queryName) {
      params.append('stnm', queryName);
    }

    if (queryArea) {
      params.append('addvcd', queryArea);
    }

    if (queryTown) {
      params.append('zhencode', queryTown);
    }

    if (querySource) {
      params.append('stsys', querySource);
    }

    const response = await shjApi.post('/shuihuanjing/chengpumpvideort/view', params, {
      headers: {
        token: ctx.headers.token
      }
    });
    
    if (response.data) {
        const { code, data } = response.data

        // const list = data
        let list = []
        if (vision == '1') {
          list = data.filter(item => item.stcd) || []
        } else if (vision == '2') {
          list = data.filter(item => item.faccd) || []
        }

        const totalCount = list.length || 0
        
        if (code == '0000') {
          const statusCount = {
            '全部': totalCount,
            '水情正常': 0,
            '水情延迟': 0,
            '水情缺失': 0,
            '内江缺失': 0,
            '外江缺失': 0,
            '工情正常': 0,
            '工情缺失': 0,
            '视频全部在线': 0,
            '视频部分在线': 0,
            '视频全部离线': 0,
            '视频缺失': 0
          };

          const statusCount_inventory = {
            '全部': 0,
            '水情正常': 0,
            '水情延迟': 0,
            '水情缺失': 0,
            '内江缺失': 0,
            '外江缺失': 0,
            '工情正常': 0,
            '工情缺失': 0,
            '视频全部在线': 0,
            '视频部分在线': 0,
            '视频全部离线': 0,
            '视频缺失': 0,
          };
          
          const mappedList = list.map((item) => {
            const stsysVal = item.stsys
            // const isDevice = stsysVal !== '镇街水利所' && stsysVal !== '禅城区水务局'  && stsysVal !== '南海排总';
            const isDevice = stsysVal === '物联网平台' || stsysVal === '水务工程监测设施建设项目'

            if (isDevice) {
              item['__custom_source'] = stsysVal;
            } else {
              const sourceObj = bzSourceList.find(child => child.stcd === item.stcd)
              item['__custom_source'] = sourceObj ? sourceObj.stsys : '--';
              statusCount_inventory['全部'] += 1
            }

            // 统一水情状态字段
            item.__custom_levelStatus = item.pumpStatus

            if (item.pmenDetail) {
              item['__custom_detail'] = JSON.parse(item.pmenDetail)
              item['__custom_detailStatus'] = '正常'
            } else {
              item['__custom_detail'] = null
              item['__custom_detailStatus'] = '缺失'
            }

            if (item.videoDetail) {
              item['__custom_videoDetail'] = JSON.parse(item.videoDetail)
              const onArr = item['__custom_videoDetail'].filter(child => child['STATUS'] === 'ON') || []
              const offArr = item['__custom_videoDetail'].filter(child => child['STATUS'] === 'OFF') || []
              
              if (onArr.length === item['__custom_videoDetail'].length) {
                item['__custom_videoDetailStatus'] = '全部在线'
              } else if (offArr.length === item['__custom_videoDetail'].length) {
                item['__custom_videoDetailStatus'] = '全部离线'
              } else {
                item['__custom_videoDetailStatus'] = '部分在线'
              }
            } else {
              item['__custom_videoDetail'] = null
              item['__custom_videoDetailStatus'] = '缺失'
            }

            if (item['__custom_levelStatus'] === '正常') {
              statusCount['水情正常'] += 1
              if (!isDevice) {
                statusCount_inventory['水情正常'] += 1
              }
            }

            if (item['__custom_levelStatus'] === '延迟') {
              statusCount['水情延迟'] += 1
              if (!isDevice) {
                statusCount_inventory['水情延迟'] += 1
              }
            }

            if (item['inpoolLevelStatus'] === '缺失') {
              statusCount['内江缺失'] += 1
              if (!isDevice) {
                statusCount_inventory['内江缺失'] += 1
              }
            }

            if (item['outpoolLevelStatus'] === '缺失') {
              statusCount['外江缺失'] += 1
              if (!isDevice) {
                statusCount_inventory['外江缺失'] += 1
              }
            }

            if (item['__custom_levelStatus'] === '缺失') {
              statusCount['水情缺失'] += 1
              if (!isDevice) {
                statusCount_inventory['水情缺失'] += 1
              }
            }

            if (item['__custom_detailStatus'] === '正常') {
              statusCount['工情正常'] += 1
              if (!isDevice) {
                statusCount_inventory['工情正常'] += 1
              }
            }

            if (item['__custom_detailStatus'] === '缺失') {
              statusCount['工情缺失'] += 1
              if (!isDevice) {
                statusCount_inventory['工情缺失'] += 1
              }
            }

            if (item['__custom_videoDetailStatus'] === '全部在线') {
              statusCount['视频全部在线'] += 1
              if (!isDevice) {
                statusCount_inventory['视频全部在线'] += 1
              }
            }

            if (item['__custom_videoDetailStatus'] === '部分在线') {
              statusCount['视频部分在线'] += 1
              if (!isDevice) {
                statusCount_inventory['视频部分在线'] += 1
              }
            }

            if (item['__custom_videoDetailStatus'] === '全部离线') {
              statusCount['视频全部离线'] += 1
              if (!isDevice) {
                statusCount_inventory['视频全部离线'] += 1
              }
            }

            if (item['__custom_videoDetailStatus'] === '缺失') {
              statusCount['视频缺失'] += 1
              if (!isDevice) {
                statusCount_inventory['视频缺失'] += 1
              }
            }

            delete item.pmenNum
            delete item.pmenDetail
            delete item.videoNum
            delete item.videoDetail
            delete item.stsys
            
            return {
              ...item
            };
          });

          const resObj = { statusCount, statusCount_inventory }

          if (isTotal == '0') {
            resObj.list = mappedList
            // resObj.list = mappedList.slice((pageNum - 1) * pageSize, pageNum * pageSize)
            // resObj.count = totalCount
            // resObj.pageNum = pageNum
            // resObj.pageSize = pageSize
          }

          ctx.body = Response.success(resObj)
        } else {
          ctx.body = Response.error('获取数据失败')
        }
    } else {
      console.error('获取数据失败:');
      ctx.body = Response.error('获取数据失败');
    }
  } catch (err) {
    console.error('请求失败:', err);
    ctx.body = Response.error('获取数据失败')
  }
};
